var webSocket;
var currentNick = null;
var currentGroup = null;
var heartbeatInterval = null;
var chatHistory = {};
var joinedRooms = [];
var displayedMessageIds = {};

// 新增：文件接收相关变量
let fileBuffer = [];
let receivedSize = 0;
let expectedSize = 0;
let fileName = '';

const token = sessionStorage.getItem('token');
if (token) {
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
}

function startHeartbeat() {
    heartbeatInterval = setInterval(() => {
        if (webSocket.readyState === WebSocket.OPEN) {
            const pingMsg = { type: "ping" };
            const pingWithHeader = addHeader(JSON.stringify(pingMsg)); // 关键修改
            webSocket.send(pingWithHeader);
        }
    }, 30000);
}
function stopHeartbeat() {
    clearInterval(heartbeatInterval);
}

if (window.WebSocket) {
    webSocket = new WebSocket("ws://localhost:53134/ws");
    // 使用本机地址
    //webSocket = new WebSocket("ws://192.168.68.3:53134/ws");
} else {
    alert("抱歉，您的浏览器不支持WebSocket协议!");
}

//------------------------------
//-- 核心修改：区分消息类型处理 --
//------------------------------
function addHeader(message) {
    const type = 1;
    const encoded = btoa(unescape(encodeURIComponent(message)));
    return `${type}|${encoded.length}|${encoded}`;
}

function parseHeader(data) {
    const parts = data.split('|', 3);
    if (parts.length !== 3) throw new Error('Invalid message format');
    const decoded = decodeURIComponent(escape(atob(parts[2])));
    return {
        type: parseInt(parts[0]),
        length: parseInt(parts[1]),
        message: decoded
    }; // 修复缺少的分号和大括号
}

// 新增：处理二进制文件分片
function handleFileChunk(chunk) {
    if (!fileName || !expectedSize) {
        console.log("未设置文件名或文件大小，忽略分片");
        return;
    }

    // 将分片转为 ArrayBuffer 并存储
    const reader = new FileReader();
    reader.onload = (e) => {
        console.log("文件分片读取完成，大小: " + e.target.result.byteLength);
        fileBuffer.push(new Uint8Array(e.target.result));
        receivedSize += e.target.result.byteLength;

        // 显示接收进度
        const progress = Math.min((receivedSize / expectedSize) * 100, 100);
        setMessageInnerHTML(`[系统] ${fileName} 接收进度: ${progress.toFixed(2)}%`);
        console.log("文件接收进度: " + progress + "%");

        // 接收完成时生成下载链接
        if (receivedSize >= expectedSize) {
            console.log("文件接收完成，开始合并分片");
            const fullData = new Uint8Array(receivedSize);
            let offset = 0;
            fileBuffer.forEach(buf => {
                fullData.set(buf, offset);
                offset += buf.length;
            });
            const blob = new Blob([fullData], { type: 'application/octet-stream' });
            const url = URL.createObjectURL(blob);
            setMessageInnerHTML(
                `[系统] ${fileName} 接收完成: <a href="${url}" download="${fileName}">点击下载</a>`
            );
            console.log("文件合并完成，生成下载链接");
            // 重置状态
            fileBuffer = [];
            receivedSize = 0;
            fileName = '';
            expectedSize = 0;
        }
    };
    reader.onerror = () => {
        console.error("文件分片读取失败");
    };
    reader.readAsArrayBuffer(chunk);
}

// 修改后的 onmessage 处理逻辑
webSocket.onmessage = function (event) {
    // 处理二进制消息
    if (event.data instanceof ArrayBuffer || event.data instanceof Blob) {
        console.log("收到二进制消息，开始处理文件分片");
        handleFileChunk(event.data);
        return;
    }

    // 处理文本消息
    try {
        const { type, length, message } = parseHeader(event.data);
        console.log("解析消息包头成功，类型: " + type + ", 长度: " + length);
        const parsedData = JSON.parse(message);
        console.log("解析消息内容成功: ", parsedData);
        if (parsedData.group !== currentGroup) {
            console.log("消息不属于当前群组，忽略");
            return;
        }

        // 处理文件元数据
        if (parsedData.type === 'file_forward') {
            // 重置接收状态
            fileName = parsedData.fileName;
            expectedSize = parseInt(parsedData.fileSize);
            receivedSize = 0;
            fileBuffer = [];
            setMessageInnerHTML(`[系统] 开始接收文件: ${fileName} (${formatFileSize(expectedSize)})`);
            console.log("开始接收文件: " + fileName + ", 大小: " + expectedSize);
            return;
        }

        // 原有消息处理逻辑
        processMessage(parsedData);
    } catch (error) {
        console.error('解析消息时出错:', error);
    }
};

// 辅助函数：生成消息ID
function generateMessageId(parsedData) {
    const sessionId = parsedData.sessionId || 'unknown';
    switch (parsedData.type) {
        case 'file_forward': return `file_forward-${parsedData.sendUser}-${parsedData.fileName}-${Date.now()}`; // 添加时间戳
        case 'file_meta': return `file_meta-${parsedData.fileName}-${sessionId}`;
        case 'online': return `online-${parsedData.group}-${parsedData.user}-${sessionId}`;
        case 'switch': return `switch-${parsedData.sendUser}-${sessionId}`;
        case 'file': return `file-${parsedData.sendUser}-${sessionId}`;
        default: return `${parsedData.type}-${parsedData.sendUser}-${sessionId}`;
    }
}

// 辅助函数：处理消息内容
function processMessage(parsedData) {
    switch (parsedData.type) {
        case 'enter':
            setMessageInnerHTML(`[系统通知] ${parsedData.sendUser} ${parsedData.msg}`);
            break;
        case 'msg':
            setMessageInnerHTML(`${parsedData.sendUser}: ${parsedData.msg}`);
            break;
        case 'online':
            updateOnlineCount(parsedData.count);
            if (parsedData.action === 'leave' && !parsedData.isSwitch) {
                setMessageInnerHTML(`[系统通知] ${parsedData.user} 离开了群`);
            }
            break;
        case 'switch':
            if (parsedData.sendUser !== currentNick) {
                setMessageInnerHTML(`[系统通知] ${parsedData.sendUser} 切换到 ${parsedData.newGroup}`);
            }
            break;
        case 'image':
            setMessageInnerHTML(`${parsedData.sendUser}: <img src="${parsedData.msg}" style="max-width:200px">`);
            break;
        // 新增 case 分支：
        case 'file_meta':
            expectedSize = parseInt(parsedData.fileSize); // 转为数值类型
            fileName = parsedData.fileName;
            setMessageInnerHTML(`[系统] 开始接收文件: ${fileName} (${formatFileSize(expectedSize)})`);
            break;
        // 修改 processMessage 函数中的 case 分支：
        case 'file_forward':
            // 显示发送者和文件信息
            setMessageInnerHTML(
                `[文件接收] ${parsedData.sendUser} 发送了文件: ${parsedData.fileName} (${formatFileSize(parsedData.fileSize)}) [接收中...]`
            );
            // 初始化接收上下文
            fileName = parsedData.fileName;
            expectedSize = parseInt(parsedData.fileSize);
            receivedSize = 0;
            fileBuffer = [];
            break;
    }
}

webSocket.onclose = function () {
    stopHeartbeat();
    fileBuffer = []; // 重置文件接收状态
};